import org.apache.commons.lang.StringUtils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

/**
 * Created by sToa on 2014/12/17.
 */
public class Java2XML {


    public void javaToXml() {

        try {
            User userA = new User();
            userA.setName("西瓜");
            userA.setAge(26);
            userA.setSex("男");
            userA.setId(1);

            User userB = new User();
            userB.setName("冬瓜");
            userB.setAge(19);
            userB.setSex("女");
            userB.setId(2);

            User userC = new User();
            userC.setName("南瓜");
            userC.setAge(22);
            userC.setSex("男");
            userC.setId(3);

            Users users = new Users();
            List<User> list = users.getUserList();
            list.add(userA);
            list.add(userB);
            list.add(userC);

            bean2Xml(users);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void XmlTojava() {
       Users users = (Users)xml2Bean(Users.class, "D:\\WorkSpace-IDE\\parser\\src\\users.xml");
       for(User user: users.getUserList())
       {
           System.out.println(user.getName());
       }
    }

    public static void bean2Xml(Object bean) {
        JAXBContext jaxbContext;
        if (null == bean)
            return;
        try {
            //下面代码将对象转变为xml
            jaxbContext = JAXBContext.newInstance(bean.getClass());
            Marshaller marshaller = jaxbContext.createMarshaller();
            //输出格式化
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(bean, System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将生成的xml转换为对象
     * @param zClass 转换为实例的对象类类型
     * @param xmlPath 需要转换的xml路径
     */
    public static Object xml2Bean(Class<?> zClass, String xmlPath) {
        Object obj = null;
        JAXBContext jaxbContext = null;
        if (StringUtils.isBlank(xmlPath))
            return obj;
        try {
            jaxbContext = JAXBContext.newInstance(zClass);
            // if without "utf-8", Invalid byte 2 of 2-byte UTF-8 sequence.
            InputStream is = new FileInputStream(new File(xmlPath));
            Unmarshaller umarshaller = jaxbContext.createUnmarshaller();
            obj = (Object) umarshaller.unmarshal(is);
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static void main(String[] args){
       new Java2XML().javaToXml();
    }
}
